<?php
namespace com\rainiswalking\sonar_report\lib;


class CommonUtil {
    public static function array_sort($array, $on, $order=SORT_ASC) {
        $new_array = array();
        $sortable_array = array();

        if (count($array) > 0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }

            switch ($order) {
                case SORT_ASC:
                    asort($sortable_array);
                    break;
                case SORT_DESC:
                    arsort($sortable_array);
                    break;
            }

            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $array[$k];
            }
        }

        return $new_array;
    }

    public static function get_field_value($arr, $field, $default) {
        if (isset($arr[$field]) && !empty($arr[$field])) {
            return $arr[$field];
        }

        return $default;
    }

    public static function implode($data, $name) {
        $arr = array();
        foreach ($data as $row) {
            $arr[] = $row[$name];
        }

        return implode($arr, ',');
    }

    public static function build_map($data, $key) {
        $arr = array();
        foreach ($data as $row) {
            $arr[$row[$key]] = $row;
        }

        return $arr;
    }

    public static function assert_field_required($arr, $field, $desc=null) {
        if (!isset($arr[$field]) || empty($arr[$field])) {
            if ($desc == null) {
                $desc = $field.' required';
            }
            throw new \Exception($desc);
        }
    }

    public static function log_info($msg) {
        self::log('INFO', $msg);
    }

    public static function log_error($msg) {
        self::log('ERROR', $msg);
    }

    public static function log_warn($msg) {
        self::log('WARN', $msg);
    }

    public static function log_debug($msg) {
        self::log('DEBUG', $msg);
    }

    static function log($level, $msg) {
        $msg = date('[Y-m-d H:i:s]')."\t".$level."\t".$msg;
        error_log($msg."\r\n", 3, 'app.log');
    }

}